#![allow(unused_imports,dead_code,unused_assignments)]
use axum::{
    extract::{Form, Query, Json, Multipart,DefaultBodyLimit},
    routing::{get,post},
    response::Response,
    body::{Body, Bytes},
    Router
};
use crate::domain::GoodsBean;
use crate::domain::GoodsQueryRequest;
use crate::serviceimpl::goods_service::activate_all_goodses as service_activate_all_goodses;
use crate::serviceimpl::goods_service::activate_goods as service_activate_goods;
use crate::serviceimpl::goods_service::add_goods as service_add_goods;
use crate::serviceimpl::goods_service::clone_all_goodses as service_clone_all_goodses;
use crate::serviceimpl::goods_service::clone_goods as service_clone_goods;
use crate::serviceimpl::goods_service::count_search_goodses_by_fields_records as service_count_search_goodses_by_fields_records;
use crate::serviceimpl::goods_service::delete_all_goodses as service_delete_all_goodses;
use crate::serviceimpl::goods_service::delete_goods as service_delete_goods;
use crate::serviceimpl::goods_service::find_goods_by_id as service_find_goods_by_id;
use crate::serviceimpl::goods_service::find_goods_by_name as service_find_goods_by_name;
use crate::serviceimpl::goods_service::list_active_goodses as service_list_active_goodses;
use crate::serviceimpl::goods_service::list_all_goodses as service_list_all_goodses;
use crate::serviceimpl::goods_service::search_goodses_by_fields as service_search_goodses_by_fields;
use crate::serviceimpl::goods_service::search_goodses_by_fields_by_page as service_search_goodses_by_fields_by_page;
use crate::serviceimpl::goods_service::soft_delete_all_goodses as service_soft_delete_all_goodses;
use crate::serviceimpl::goods_service::soft_delete_goods as service_soft_delete_goods;
use crate::serviceimpl::goods_service::toggle_goods as service_toggle_goods;
use crate::serviceimpl::goods_service::toggle_one_goods as service_toggle_one_goods;
use crate::serviceimpl::goods_service::update_goods as service_update_goods;
use crate::serviceimpl::goods_type_service::find_goods_type_by_id as service_find_goods_type_by_id;
use crate::utils::excel_util::export_excel_workbook_with_image;
use crate::utils::pdf_util::export_pdf_with_images;
use serde::{Deserialize};
use serde_json::{Value,Map};
use std::collections::HashMap;
use std::fs;
use std::sync::Mutex;
use tower_http::{trace::TraceLayer};


lazy_static! {
	static ref TEMP_GOODS_IMAGES:Mutex<HashMap<String,String>> = Mutex::new(HashMap::new());
}

pub fn store_goods_picture(key:String,photo:String) {
	TEMP_GOODS_IMAGES.lock().unwrap().insert(key,photo);
}

pub fn pick_goods_picture(key:String) ->String {
	let ret:Option<String> = TEMP_GOODS_IMAGES.lock().unwrap().get(&key).cloned();
	TEMP_GOODS_IMAGES.lock().unwrap().insert(key,"".to_string());
	if ret.is_none() {
		return "".to_string();
	}
	ret.as_ref().unwrap().to_string()
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GoodsRequest {
	pub id: Option<i64>,
	pub name: Option<String>,
	pub active: Option<bool>,
	pub price: Option<f64>,
	pub intro: Option<String>,
	pub stock: Option<i32>,
	pub goods_type_id: Option<i64>,
	pub is_scroll: Option<bool>,
	pub is_hot: Option<bool>,
	pub is_new: Option<bool>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdsRequest {
	pub ids: String,
}

pub fn goods_controller() -> Router {
	Router::new()
	.route("/listAllGoodses", post(list_all_goodses))
	.route("/updateGoods", post(update_goods))
	.route("/deleteGoods", post(delete_goods))
	.route("/addGoods", post(add_goods))
	.route("/softDeleteGoods", post(soft_delete_goods))
	.route("/findGoodsById", post(find_goods_by_id))
	.route("/findGoodsByName", post(find_goods_by_name))
	.route("/listActiveGoodses", post(list_active_goodses))
	.route("/deleteAllGoodses", post(delete_all_goodses))
	.route("/softDeleteAllGoodses", post(soft_delete_all_goodses))
	.route("/toggleGoods", post(toggle_goods))
	.route("/toggleOneGoods", post(toggle_one_goods))
	.route("/searchGoodsesByFieldsByPage", post(search_goodses_by_fields_by_page))
	.route("/activateGoods", post(activate_goods))
	.route("/activateAllGoodses", post(activate_all_goodses))
	.route("/exportGoodses", get(export_goodses))
	.route("/exportGoodsesPDF", get(export_goodses_pdf))
	.route("/filterGoodsesExcel", get(filter_goodses_excel))
	.route("/filterGoodsesPDF", get(filter_goodses_pdf))
	.route("/cloneGoods", post(clone_goods))
	.route("/cloneAllGoodses", post(clone_all_goodses))
	.route("/checkAccessGoods", get(check_access_goods))
	.route("/addUploadGoodsCover", post(add_upload_goods_cover))
	.route("/addUploadGoodsImage1", post(add_upload_goods_image1))
	.route("/addUploadGoodsImage2", post(add_upload_goods_image2))
	.layer(DefaultBodyLimit::max(2*1024*1024))
	.layer(TraceLayer::new_for_http())
}
pub async fn activate_all_goodses(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_activate_all_goodses(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn activate_goods(Form(goods_request):Form<GoodsRequest>) ->String {
	let id = goods_request.id.unwrap_or_default();
	let _result = service_activate_goods(id).await;
	match _result {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn add_goods(Json(goods_request):Json<GoodsRequest>) ->String {
	let id = goods_request.id.unwrap_or_default();
	let name = goods_request.name.unwrap_or_default();
	let active = goods_request.active.unwrap_or_default();
	let price = goods_request.price.unwrap_or_default();
	let intro = goods_request.intro.unwrap_or_default();
	let stock = goods_request.stock.unwrap_or_default();
	let goods_type_id = goods_request.goods_type_id.unwrap_or_default();
	let is_scroll = goods_request.is_scroll.unwrap_or_default();
	let is_hot = goods_request.is_hot.unwrap_or_default();
	let is_new = goods_request.is_new.unwrap_or_default();
	let my_cover = pick_goods_picture("cover".to_string());
	let my_image1 = pick_goods_picture("image1".to_string());
	let my_image2 = pick_goods_picture("image2".to_string());

	let goods = GoodsBean{
	id : id,
	name : name,
	active : active,
	cover : my_cover,
	image1 : my_image1,
	image2 : my_image2,
	price : price,
	intro : intro,
	stock : stock,
	goods_type_id : goods_type_id,
	is_scroll : is_scroll,
	is_hot : is_hot,
	is_new : is_new,
	};
	
	let _result = service_add_goods(goods).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn add_upload_goods_cover(mut multipart:Multipart) ->String {
		while let Some(field) = multipart.next_field().await.unwrap() {
			let name = field.name().unwrap().to_string();
			if name == "files[]" {
				let content_type = field.content_type().unwrap().to_string();
				if content_type.starts_with("image/") {
					let data = field.bytes().await.unwrap();
					let data_str = base64::encode(data);
					store_goods_picture("cover".to_string(),data_str.clone());
					
					let mut map = Map::new();
					map.insert("success".to_string(), Value::from(true));
					map.insert(
						"rows".to_string(),
						Value::from(data_str.clone()),
					);
				
					let resultjson = serde_json::to_string_pretty(&map).unwrap();
					return resultjson;
				}
			}
		}
		r#"{  "rows": null,  "success": true}"#.to_string()
}

pub async fn add_upload_goods_image1(mut multipart:Multipart) ->String {
		while let Some(field) = multipart.next_field().await.unwrap() {
			let name = field.name().unwrap().to_string();
			if name == "files[]" {
				let content_type = field.content_type().unwrap().to_string();
				if content_type.starts_with("image/") {
					let data = field.bytes().await.unwrap();
					let data_str = base64::encode(data);
					store_goods_picture("image1".to_string(),data_str.clone());
					
					let mut map = Map::new();
					map.insert("success".to_string(), Value::from(true));
					map.insert(
						"rows".to_string(),
						Value::from(data_str.clone()),
					);
				
					let resultjson = serde_json::to_string_pretty(&map).unwrap();
					return resultjson;
				}
			}
		}
		r#"{  "rows": null,  "success": true}"#.to_string()
}

pub async fn add_upload_goods_image2(mut multipart:Multipart) ->String {
		while let Some(field) = multipart.next_field().await.unwrap() {
			let name = field.name().unwrap().to_string();
			if name == "files[]" {
				let content_type = field.content_type().unwrap().to_string();
				if content_type.starts_with("image/") {
					let data = field.bytes().await.unwrap();
					let data_str = base64::encode(data);
					store_goods_picture("image2".to_string(),data_str.clone());
					
					let mut map = Map::new();
					map.insert("success".to_string(), Value::from(true));
					map.insert(
						"rows".to_string(),
						Value::from(data_str.clone()),
					);
				
					let resultjson = serde_json::to_string_pretty(&map).unwrap();
					return resultjson;
				}
			}
		}
		r#"{  "rows": null,  "success": true}"#.to_string()
}

pub async fn check_access_goods() ->String {
	r#"{  "rows": null,  "success": true}"#.to_string()
}

pub async fn clone_all_goodses(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_clone_all_goodses(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn clone_goods(Form(goods_request):Form<GoodsRequest>) ->String {
	let id = goods_request.id.unwrap_or_default();
	let _result = service_clone_goods(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_all_goodses(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_delete_all_goodses(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn delete_goods(Form(goods_request):Form<GoodsRequest>) ->String {
	let id = goods_request.id.unwrap_or_default();
	let _result = service_delete_goods(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn export_goodses() ->Response<Body> {
	let list = service_list_all_goodses().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "商品信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"封面".to_string(),"图片一".to_string(),"图片二".to_string(),"价格".to_string(),"简介".to_string(),"存货".to_string(),"类型".to_string(),"滚动".to_string(),"热门商品".to_string(),"等级".to_string()];
	let is_images = vec![false,false,false,true,true,true,false,false,false,false,false,false,false];
	for goods in list {
		let goods_type_id = goods.goods_type_id;
		let mut goods_type_id_name0 = "".to_string();
		if goods_type_id > 0 {
			let goods_type_id_type0 = service_find_goods_type_by_id(goods_type_id).await.unwrap();
			if goods_type_id_type0.id != 0 {
				goods_type_id_name0 = goods_type_id_type0.name;
			}
		}

		let row = vec![goods.id.to_string(),goods.name,goods.active.to_string(),goods.cover,goods.image1,goods.image2,goods.price.to_string(),goods.intro,goods.stock.to_string(),goods_type_id_name0,goods.is_scroll.to_string(),goods.is_hot.to_string(),goods.is_new.to_string()];
		contents.push(row);
	}

	let full_file_path = "./template/temp/goodses.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);
	
	
	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=goodses.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn export_goodses_pdf() ->Response<Body> {
	let list = service_list_all_goodses().await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "商品信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"封面".to_string(),"图片一".to_string(),"图片二".to_string(),"价格".to_string(),"简介".to_string(),"存货".to_string(),"类型".to_string(),"滚动".to_string(),"热门商品".to_string(),"等级".to_string()];
	let is_images = vec![false,false,false,true,true,true,false,false,false,false,false,false,false];
	for goods in list {
		let goods_type_id = goods.goods_type_id;
		let mut goods_type_id_name0 = "".to_string();
		if goods_type_id > 0 {
			let goods_type_id_type0 = service_find_goods_type_by_id(goods_type_id).await.unwrap();
			if goods_type_id_type0.id != 0 {
				goods_type_id_name0 = goods_type_id_type0.name;
			}
		}

		let row = vec![goods.id.to_string(),goods.name,goods.active.to_string(),goods.cover,goods.image1,goods.image2,goods.price.to_string(),goods.intro,goods.stock.to_string(),goods_type_id_name0,goods.is_scroll.to_string(),goods.is_hot.to_string(),goods.is_new.to_string()];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);
	
	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=goodses.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_goodses_excel(Query(goods_query_request):Query<GoodsQueryRequest>) ->Response<Body> {
	let list = service_search_goodses_by_fields(goods_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "商品信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"封面".to_string(),"图片一".to_string(),"图片二".to_string(),"价格".to_string(),"简介".to_string(),"存货".to_string(),"类型".to_string(),"滚动".to_string(),"热门商品".to_string(),"等级".to_string()];
	let is_images = vec![false,false,false,true,true,true,false,false,false,false,false,false,false];
	for goods in list {
		let goods_type_id = goods.goods_type_id;
		let mut goods_type_id_name0 = "".to_string();
		if goods_type_id > 0 {
			let goods_type_id_type0 = service_find_goods_type_by_id(goods_type_id).await.unwrap();
			if goods_type_id_type0.id != 0 {
				goods_type_id_name0 = goods_type_id_type0.name;
			}
		}

		let row = vec![goods.id.to_string(),goods.name,goods.active.to_string(),goods.cover,goods.image1,goods.image2,goods.price.to_string(),goods.intro,goods.stock.to_string(),goods_type_id_name0,goods.is_scroll.to_string(),goods.is_hot.to_string(),goods.is_new.to_string()];
		contents.push(row);
	}

	let full_file_path = "./template/temp/goodses.xlsx";
	export_excel_workbook_with_image(full_file_path.to_string(),sheet_name, headers, contents, is_images);
	
	
	let data = fs::read(full_file_path).unwrap();
	let _ = fs::remove_file(full_file_path);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=goodses.xlsx")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn filter_goodses_pdf(Query(goods_query_request):Query<GoodsQueryRequest>) ->Response<Body> {
	let list = service_search_goodses_by_fields(goods_query_request).await.unwrap();
	let mut contents : Vec<Vec<String>> = Vec::new();
	let sheet_name = "商品信息表".to_string();
	let headers = vec!["序号".to_string(),"名字".to_string(),"活跃".to_string(),"封面".to_string(),"图片一".to_string(),"图片二".to_string(),"价格".to_string(),"简介".to_string(),"存货".to_string(),"类型".to_string(),"滚动".to_string(),"热门商品".to_string(),"等级".to_string()];
	let is_images = vec![false,false,false,true,true,true,false,false,false,false,false,false,false];
	for goods in list {
		let goods_type_id = goods.goods_type_id;
		let mut goods_type_id_name0 = "".to_string();
		if goods_type_id > 0 {
			let goods_type_id_type0 = service_find_goods_type_by_id(goods_type_id).await.unwrap();
			if goods_type_id_type0.id != 0 {
				goods_type_id_name0 = goods_type_id_type0.name;
			}
		}

		let row = vec![goods.id.to_string(),goods.name,goods.active.to_string(),goods.cover,goods.image1,goods.image2,goods.price.to_string(),goods.intro,goods.stock.to_string(),goods_type_id_name0,goods.is_scroll.to_string(),goods.is_hot.to_string(),goods.is_new.to_string()];
		contents.push(row);
	}

	let data = export_pdf_with_images(sheet_name, headers, contents, is_images);

	Response::builder()
	.header("Content-Type", "application/octet-stream")
	.header("Content-Disposition", "attachment; filename=goodses.pdf")
	.header("Content-Transfer-Encoding", "binary")
	.body(Body::from(data))
	.unwrap()
}

pub async fn find_goods_by_id(Form(goods_request):Form<GoodsRequest>) ->String {
	let id = goods_request.id.unwrap_or_default();
	let goods = service_find_goods_by_id(id).await;
	match goods {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(goods) => {
			let json = serde_json::to_string_pretty(&goods).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn find_goods_by_name(Form(goods_request):Form<GoodsRequest>) ->String {
	let name = goods_request.name.unwrap_or_default();
	let goods = service_find_goods_by_name(name).await;
	match goods {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(goods) => {
			let json = serde_json::to_string_pretty(&goods).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn list_active_goodses() ->String {
	let goodses = service_list_active_goodses().await;
	match goodses {
		Err(_) => {
			println!("Error!");
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(goodses) => {
			let json = serde_json::to_string_pretty(&goodses).unwrap();
			//println!("{}", json);

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			//println!("{}", resultjson);
			return resultjson;
		}
	}
}

pub async fn list_all_goodses() ->String {
	let goodses = service_list_all_goodses().await;
	match goodses {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(goodses) => {
			let json = serde_json::to_string_pretty(&goodses).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn search_goodses_by_fields_by_page(Form(goods_query_request):Form<GoodsQueryRequest>) ->String {
	let goodses = service_search_goodses_by_fields_by_page(goods_query_request.clone()).await;
	let total = service_count_search_goodses_by_fields_records(goods_query_request.clone()).await.unwrap().count_num;
	match goodses {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(goodses) => {
			let json = serde_json::to_string_pretty(&goodses).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert("total".to_string(), Value::from(total));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);
		
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_all_goodses(Form(ids_request):Form<IdsRequest>) ->String {
	let ids = ids_request.ids;
	let string_ids:Vec<&str> = ids.split(',').collect();
	let mut ids:Vec<i64> = Vec::new();

	let vecter_iterator = string_ids.iter();
	for id in vecter_iterator {
		ids.push(id.parse::<i64>().unwrap());
	}

	let _result = service_soft_delete_all_goodses(ids).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn soft_delete_goods(Form(goods_request):Form<GoodsRequest>) ->String {
	let id = goods_request.id.unwrap_or_default();
	let _result = service_soft_delete_goods(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_goods(Form(goods_request):Form<GoodsRequest>) ->String {
	let id = goods_request.id.unwrap_or_default();
	let _result = service_toggle_goods(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn toggle_one_goods(Form(goods_request):Form<GoodsRequest>) ->String {
	let id = goods_request.id.unwrap_or_default();
	let _result = service_toggle_one_goods(id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn update_goods(Json(goods_request):Json<GoodsRequest>) ->String {
	let id = goods_request.id.unwrap_or_default();
	let name = goods_request.name.unwrap_or_default();
	let active = goods_request.active.unwrap_or_default();
	let price = goods_request.price.unwrap_or_default();
	let intro = goods_request.intro.unwrap_or_default();
	let stock = goods_request.stock.unwrap_or_default();
	let goods_type_id = goods_request.goods_type_id.unwrap_or_default();
	let is_scroll = goods_request.is_scroll.unwrap_or_default();
	let is_hot = goods_request.is_hot.unwrap_or_default();
	let is_new = goods_request.is_new.unwrap_or_default();
	let _current_goods = service_find_goods_by_id(id).await.unwrap();
	let current_cover = _current_goods.cover;
	let mut my_cover = pick_goods_picture("cover".to_string());
	if my_cover.len() == 0 && current_cover.len()>0 {
		my_cover = current_cover;
	}
	let current_image1 = _current_goods.image1;
	let mut my_image1 = pick_goods_picture("image1".to_string());
	if my_image1.len() == 0 && current_image1.len()>0 {
		my_image1 = current_image1;
	}
	let current_image2 = _current_goods.image2;
	let mut my_image2 = pick_goods_picture("image2".to_string());
	if my_image2.len() == 0 && current_image2.len()>0 {
		my_image2 = current_image2;
	}

	let goods = GoodsBean{
	id : id,
	name : name,
	active : active,
	cover : my_cover,
	image1 : my_image1,
	image2 : my_image2,
	price : price,
	intro : intro,
	stock : stock,
	goods_type_id : goods_type_id,
	is_scroll : is_scroll,
	is_hot : is_hot,
	is_new : is_new,
	};
	
	let _result = service_update_goods(goods).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);
			
			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

